import { useEffect, useMemo, useRef, useState } from "react";
import eventBus from "../eventBus";
import { AntdTableData } from "../sku-admin/sku-admin-table";
import { FormValues } from "../sku-admin";
import { Tag } from "antd";

function SkuFront() {
  const [formValues, setFormValues] = useState<FormValues["options"]>([]);
  const [dataSource, setDataSource] = useState<AntdTableData[]>([]);
  const checkArray = useRef<string[][]>([]);

  const handleButtonClicked = (message: {
    formValues: FormValues["options"];
    dataSource: AntdTableData[];
  }) => {
    const { formValues: values, dataSource } = message;
    checkArray.current = dataSource
      .filter((item) => item.inventory !== "0") // 过滤掉 inventory 为 0 的记录
      .map((item) => {
        const result = [];
        for (const key in item) {
          if (key !== "price" && key !== "key" && key !== "inventory") {
            result.push(`${key}-${item[key as keyof AntdTableData]}`);
          }
        }
        return result;
      }); // 提取需要的字段
    console.log(values, dataSource, checkArray.current);
    setFormValues(values);
    setDataSource(dataSource);
  };

  useEffect(() => {
    eventBus.on("createFrontEndPage", handleButtonClicked);
    return () => {
      eventBus.off("createFrontEndPage", handleButtonClicked);
    };
  }, []);

  const [selectedTags, setSelectedTags] = useState<string[]>([]);

  const price = useMemo(() => {
    return formValues.length === selectedTags.length
      ? dataSource
          .filter((item) => {
            return selectedTags.every((tag) => {
              const [name, value] = tag.split("-");
              return item[name.toLowerCase() as keyof AntdTableData] === value;
            });
          })
          .reduce((acc, curr) => acc + +curr.price, 0)
      : 0;
  }, [dataSource, selectedTags]);

  const inventory = useMemo(() => {
    return formValues.length === selectedTags.length
      ? dataSource
          .filter((item) => {
            return selectedTags.every((tag) => {
              const [name, value] = tag.split("-");
              return item[name.toLowerCase() as keyof AntdTableData] === value;
            });
          })
          .reduce((acc, curr) => acc + +curr.inventory, 0)
      : 0;
  }, [dataSource, selectedTags]);

  return (
    <div style={{ padding: "20px" }}>
      <h1>SKU Front</h1>
      {formValues.map((item) => (
        <div key={item.name}>
          <p>{item.name}</p>
          {item.tags.map((tag, i) => {
            const tagId = `${item.name}-${tag}`;
            // 处理标签选择逻辑
            const hasInventory = checkArray.current.some((checkArrayItem) => {
              // 1. 检查当前标签是否在库存中
              const hasCurrentTag = checkArrayItem.includes(tagId);
              // 2. 检查所有已选标签是否都在库存中
              const hasAllSelectedTags = selectedTags.every((attr) => {
                return checkArrayItem.includes(attr);
              });
              // 3. 检查同级标签的库存情况
              const [currentTagName] = tagId.split("-");
              const hasSiblingTags = selectedTags.some((t) => t.startsWith(currentTagName));
              if (hasSiblingTags) {
                // 如果存在同级标签，需要特殊处理
                const currentTags = [
                  ...selectedTags.filter((t) => !t.startsWith(currentTagName)),
                  tagId,
                ];
                // 检查新的标签组合是否有库存
                return dataSource.some((item) => 
                  currentTags.every((tag) => {
                    const [name, value] = tag.split("-");
                    return item[name.toLowerCase() as keyof AntdTableData] === value;
                  }) && +item.inventory > 0
                );
              }
              // 4. 返回最终结果：当前标签和所有已选标签都在库存中
              return hasCurrentTag && hasAllSelectedTags;
            });
           
            return (
              <Tag
                color={
                  selectedTags.some(
                    (t) => t.startsWith(item.name) && t.endsWith(tag)
                  )
                    ? "red"
                    : "default"
                }
                key={i}
                onClick={() => {
                  if (!hasInventory) return; // If no inventory is available, it cannot be selected
                  if (selectedTags.includes(tagId)) {
                    setSelectedTags((prev) => prev.filter((t) => t !== tagId));
                  } else {
                    setSelectedTags((prev) => [
                      ...prev.filter((t) => !t.startsWith(item.name)),
                      tagId,
                    ]);
                  }
                  console.log(selectedTags, "selectedTags");
                }}
                style={{
                  fontSize: "16px",
                  cursor: hasInventory ? "pointer" : "not-allowed",
                  padding: "5px 10px",
                  opacity: hasInventory ? 1 : 0.5,
                }}
              >
                {tag}
              </Tag>
            );
          })}
        </div>
      ))}
      <div
        style={{
          color: "#333",
          fontSize: "18px",
          fontWeight: "bold",
          marginTop: "20px",
        }}
      >
        price: {price}
      </div>
      <div style={{ color: "#666", fontSize: "16px", marginTop: "10px" }}>
        inventory: {inventory}
      </div>
    </div>
  );
}

export default SkuFront;
